# -*- coding:utf-8 -*-
import MySQLdb, json
import os, time
os.sys.path.append('../../utils/constants/')
from constants import *

class messageDao(object):
    def __init__(self, mysql_conn):
        self.__nessary_list = [\
                (type(10), "recv_uid"), \
                (type(10), "message_id"), \
                (type(10), "send_uid"), \
                (type(10), "itype"), \
                (type(u''), "send_uname"), \
                (type(''), "content"), \
                (type(10), "creat_time"),]
        self.__list_size = 10
        self.__message_output_list = [\
                'recv_uid',\
                'message_id',\
                'itype',\
                'send_uid',\
                'send_uname',\
                'action_type',\
                'creat_time',\
                'content', ]
        self.__db_conn     = mysql_conn
    def get_count(self, recv_uid):
        count_item = {}
        count_item['all_count'] = 0
        count_item['unread_count'] = 0

        select_list = ['recv_uid', 'all_count', 'unread_count',]
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM message_count WHERE recv_uid = %u;' % (select_key_string, recv_uid)
        dbret = self.__db_conn.get(strSQL)
        if dbret:
            return dbret
        else:
            return count_item

    def get_list(self, recv_uid, pageno):
        select_list = self.__message_output_list
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM message WHERE recv_uid = %u ORDER BY creat_time DESC limit %u, %u;' %\
                (select_key_string, recv_uid, pageno*self.__list_size, self.__list_size)
        dbret = self.__db_conn.query(strSQL)
        if dbret:
            return dbret
        else:
            return []

#    def get_content(self, recv_uid, message_id):
#        select_list = self.__message_output_list
#        select_key_string = ', '.join(select_list)
#        strSQL = 'SELECT %s FROM message WHERE recv_uid = %u and message_id = %u;' %\
#                (select_key_string, recv_uid, message_id)
#        dbret = self.__db_conn.execute(strSQL) 
#        message_item = {}
#        if dbret:
#            cursor = self.__db_conn._db.cursor()
#            # 更新message的读取状态
#            strSQL = 'UPDATE message SET has_read = 1 WHERE recv_uid = %u and message_id = %u;' % \
#                    ( recv_uid, message_id)
#            #print strSQL
#            #print 'ret:', cursor.execute(strSQL)
#            #print 'rowcount:', cursor.rowcount
#            cursor.execute(strSQL)
#            # 更新message_count的计数
#            strSQL = 'UPDATE message_count SET unread_count = unread_count - %u WHERE recv_uid = %u;' % \
#                    ( cursor.rowcount, recv_uid, )
#            cursor.execute(strSQL)
#        return message_item

    def remove(self, recv_uid, message_id):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"

        cursor = self.__db_conn._db.cursor()
        ## 注意删除的message的已读状态
        #strSQL = 'SELECT has_read FROM message WHERE recv_uid = %u and message_id = %u;' % (recv_uid, message_id, )
        #count = cursor.execute(strSQL) 
        #if count == 0:
        #    return ret
        #
        ## 需要更新message_count表，
        #db_result = cursor.fetchone()
        #sub_read = 0
        #if db_result[0] == 0:
        #    # 未读过
        #    sub_read = 1
        #else:
        #    sub_read = 0
        #strSQL = 'UPDATE message_count SET all_count=all_count-1, unread_count=unread_count-%u WHERE recv_uid = %u;' % \
        #        ( sub_read, recv_uid, )
        ##print strSQL
        #cursor.execute(strSQL)


        # 删除message
        strSQL = 'DELETE FROM message WHERE recv_uid = %u and message_id = %u;' % (recv_uid, message_id, )
        #print strSQL
        cursor.execute(strSQL)
        # 更新计数
        if cursor.rowcount:
            strSQL = 'UPDATE message_count SET all_count=all_count-1 WHERE recv_uid = %u;' % (recv_uid, )
            #print strSQL
            cursor.execute(strSQL)
        return ret

    def clear_unread_count(self, recv_uid, ):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        strSQL = 'UPDATE message_count SET unread_count=0 WHERE recv_uid = %u;' % (recv_uid,)
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def __is_valid(self, message_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not message_item:
            ret['retcode'] = E_VALUE_NONE
            ret['message'] = 'message_item is None'
            return ret
        for key_item in self.__nessary_list:
            if not message_item.has_key(key_item[1]):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = 'field[%s] not exist' % (key_item[1], )
                return ret
            if type(message_item[key_item[1]]) != key_item[0]:
                ret['retcode'] = E_VALUE_TYPE_ERROR
                ret['message'] = 'field[%s] type error. wish[%s]' % (key_item[1], key_item[0],)
                return ret
            if None == message_item[key_item[1]]:
                ret['retcode'] = E_VALUE_IS_EMPTY
                ret['message'] = 'field[%s] empty value' % (key_item[1], )
                return ret
        return ret


    def send(self, message_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        message_item['message_id'] = 0x7FFFFFFF
        check_ret = self.__is_valid(message_item)
        if 0 !=  check_ret['retcode']:
            return check_ret
        if message_item['recv_uid'] == message_item['send_uid']:
            ret['retcode'] = E_SEND_TO_SELF
            ret['message'] = 'can not send message to self. uid[%u]' % (message_item['recv_uid'],)
            return ret
        t = time.time()
        # 分配message_id
        field_list = 'recv_uid'
        strSQL = 'INSERT INTO message_id (%s) VALUES (%u);' % ( field_list, message_item['recv_uid'],)
        #print strSQL
        self.__db_conn.execute(strSQL)
        message_id = self.__db_conn._db.insert_id()
        message_item['message_id'] = message_id
        #print '- messageDao - insertid %.6f' % (time.time() - t)
        t = time.time()

        message4insert = {}
        for key in self.__nessary_list:
            message4insert[key[1]] = message_item[key[1]]

        field_list = self.__nessary_list
        field_key_list = ''
        field_value_list = ''
        conn = self.__db_conn._db
        for  field in field_list:
            if not message4insert.has_key(field[1]):
                continue
            field_key_list += '%s, ' % (field[1],)
            if field[0] == type(10):
                field_value_list += '%u, ' % (message4insert[field[1]],)
            elif field[0] == type(''):
                field_value_list += '"%s", ' % (conn.escape_string(message4insert[field[1]]),)
            elif field[0] == type(u''):
                field_value_list += '"%s", ' % (conn.escape_string(message4insert[field[1]]),)
            else:
                assert 0
        field_key_list = field_key_list[:-2] + ' '
        field_value_list = field_value_list[:-2] + ' '

        strSQL = 'INSERT INTO message (%s) VALUES (%s);' % (field_key_list, field_value_list,)
        # -1- 插入message表
        #print strSQL
        self.__db_conn.execute(strSQL)
        #print '- messageDao - insert message %.6f' % (time.time() - t)
        t = time.time()
        # -2- 更新message_count表
        strSQL = 'INSERT INTO message_count (recv_uid, all_count, unread_count) \
                VALUES (%u, 1, 1) ON DUPLICATE KEY UPDATE \
                all_count = all_count + 1, unread_count = unread_count + 1;' % (message_item['recv_uid'],)
        #print strSQL
        self.__db_conn.execute(strSQL)
        #print '- messageDao - insert message_count %.6f' % (time.time() - t)
        t = time.time()
        return ret
